package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
    @Resource
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itheima.util.Log)")
    public Object logAround(ProceedingJoinPoint pjp) throws Throwable {


        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();

        OperateLog operateLog = new OperateLog();
        //  当前操作的用户id：暂时写死成2
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        //  当前操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //  操作的方法名
        Signature signature = pjp.getSignature();
        operateLog.setMethodName(signature.getName());
        //  操作的类名
        operateLog.setClassName(signature.getDeclaringTypeName());
        //操作方法参数
        Object[] args = pjp.getArgs();
        operateLog.setMethodParams(Arrays.toString(args));
        //操作方法返回值
        operateLog.setReturnValue(proceed==null?"":proceed.toString());
        //  当前操作的耗时
        operateLog.setCostTime(end - start);

        //插入信息
        operateLogMapper.insert(operateLog);
        return proceed;
    }
}
